from sqllex import *
import sqlite3
from Settings import DATABASE_PATH,SEP,SESSIONS_FOLDER,DATA_FOLDER
from telethon import TelegramClient
import os
import prettytable
from time import time
from Console import console


def add_group(client,name,tg_link,stay_in_group=1):
    db = SQLite3x(path=DATABASE_PATH)
    db.connect()
    ret=db.select("groups",SELECT='id',WHERE=(db['groups']['tg_link']==tg_link))
    if ret and ret==db.select("groups",SELECT='id',WHERE=(db['groups']['account_id']==client.id)):
        return
    ret=db.select("groups",SELECT='id')
    if ret:
        new_id=ret[-1][0] + 1
    else:
        new_id=0
    db["groups"].insert(
            id=new_id,
            chat_name=name,
            tg_link=tg_link,
            account_id=client.id,
            time_of_leaving=str(int(time()) + stay_in_group * 3600))
    db.disconnect()

    
def add_new_account():
    phone = input("Phone: ")
    password = input("Password (Telegram): ")
    api_id = input("Api_id: ")
    api_hash = input("Api_hash: ")
    is_active = int(input("Is active(0, 1): "))
    wallet = input("Wallet: ")
    if os.path.exists(DATABASE_PATH):
        db = SQLite3x(path=DATABASE_PATH)
        db.connect()
        ret=db.select("accounts",SELECT="id")
        if ret:
            new_id_account=ret[-1][0]+1
        else:
            new_id_account=0
        if api_id and api_hash:
            session=  SESSIONS_FOLDER + SEP + "anon" + str(new_id_account) + '.session'
            try:
                client = TelegramClient(session, int(api_id), api_hash)
                client.start()
            except sqlite3.OperationalError:
                os.mkdir(SESSIONS_FOLDER)
                print("error beacuse session folder doesnt exist")
        else:
            session=""
        db["accounts"].insert(
            id=new_id_account,
            phone=phone,
            password=password,
            api_id=api_id,
            api_hash=api_hash,
            is_active=int(is_active),
            wallet=wallet,
            session=session,
            )
        db.disconnect()
    else:
        print("!BD doesnt exist!")
        create_db()
        add_new_account()
        
def delete_old_connections(client):
    db = SQLite3x(path=DATABASE_PATH)
    db.connect()
    
    ret=db.select('groups',SELECT=["id","chat_name",'time_of_leaving'],WHERE=(db['groups']['account_id']==client.id))
    groups_to_leave=[]
    for el in ret:
        #print(time(),int(el[2]),int(time()) > int(el[2]))
        if int(time()) > int(el[2]):
            
            db.delete('groups',WHERE=(db['groups']['id']==el[0]))
            groups_to_leave.append([el[0],el[1]])
    tg_chat_to_leave = []
    for el in groups_to_leave:
        #ret=db.select('groups',SELECT="chat_name",WHERE=(db['groups']['id']==el))
        tg_chat_to_leave.append(el[1])
    db.disconnect()
    return tg_chat_to_leave
def create_db():
    try:
        os.mkdir(DATA_FOLDER)
    except:
        pass
    db = SQLite3x(                              
        path=DATABASE_PATH,                      
        template={                              
            "accounts": {                          
                "id":[INTEGER,PRIMARY_KEY],
                "phone": TEXT,   
                "password":TEXT,
                "api_id": TEXT,
                "api_hash" :TEXT,
                "is_active":INTEGER,
                "session":TEXT,  
                "wallet":TEXT    
            },
            "groups": {
                "id":[INTEGER,PRIMARY_KEY],
                "chat_name":TEXT,
                "tg_link":TEXT,
                "account_id":[INTEGER,NOT_NULL],
                "time_of_leaving":TEXT
            }
                                            
        }                                       
    )
    db.connect()
    db.disconnect()
def delete_account(id):
    
    db=SQLite3x(path=DATABASE_PATH)
    db.connect()
    session=db.select('accounts',SELECT='session',WHERE=(db['accounts']['id']==id))
    os.remove(session)
    db.delete("accounts",db["accounts"]["id"]==id)
    
    db.disconnect()

def print_accounts():
    if os.path.exists(DATABASE_PATH):
        db=SQLite3x(path=DATABASE_PATH)
        db.connect()
        pretty=prettytable.PrettyTable()
        pretty.field_names=db.get_columns_names('accounts')
        pretty.add_rows(db.select("accounts"))
        print(pretty)
        db.disconnect()

    else:
        create_db()

def get_accounts():
    if os.path.exists(DATABASE_PATH):
        db=SQLite3x(path=DATABASE_PATH)
        db.connect()
        return db.select("accounts")
    else:
        return []

def manage_accounts():
    if os.path.exists(DATABASE_PATH):
        db=SQLite3x(path=DATABASE_PATH)
        db.connect()
        while True:
            print("1.Add account\n2.Remove account\n3.Print accounts\n4.Exit")
            opt=int(input("? "))
            
            if opt==1:
                add_new_account()
            elif opt==2:
                print_accounts()
                try:
                    delete_account(int(input("Input ID of account to delete:")))
                except:
                    print("error deleting account")
                    continue
            elif opt==3:
                print_accounts()
            else:
                break
        db.disconnect()

    else:
        create_db()
def get_proxys():
    ret=[]
    try:
        with open(DATA_FOLDER+SEP+"proxy"+SEP+"http.txt","r") as f:
            for i in f.readlines():
                i=i.join(i.split())
                ip=i[:i.find(":")]
                port=i[i.find(":")+1:]
                ret.append([ip,"HTTPS",port])
    except:
        console.send_alert("error while reading http.txt")
        pass
    
    
    return ret

def _delete_all_groups(client):
    db = SQLite3x(path=DATABASE_PATH)
    db.connect()

    for el in db.select('groups',SELECT=["id"],WHERE=(db['groups']['account_id']==client.id)):
        
        db.update(
                'groups',
                SET={
                    'time_of_leaving':0,
                },
                WHERE=(db["groups"]['id']==el[0]))
    
    ret=db.select('groups',SELECT=["id","chat_name",'time_of_leaving'],WHERE=(db['groups']['account_id']==client.id))
    groups_to_leave=[]
    for el in ret:
        #print(time(),int(el[2]),int(time()) > int(el[2]))
        if int(time()) > int(el[2]):
            
            db.delete('groups',WHERE=(db['groups']['id']==el[0]))
            groups_to_leave.append([el[0],el[1]])
    tg_chat_to_leave = []
    for el in groups_to_leave:
        #ret=db.select('groups',SELECT="chat_name",WHERE=(db['groups']['id']==el))
        tg_chat_to_leave.append(el[1])
    db.disconnect()
    return tg_chat_to_leave

if __name__ == '__main__':
    create_db()
    manage_accounts()